package com.yf.zzmusic.utils;


import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件处理
 */
public class Image2Binary
{
  private static Logger log = LoggerFactory.getLogger(Image2Binary.class);

  public static byte[] toByteArray(InputStream in) throws IOException {

    ByteArrayOutputStream out=new ByteArrayOutputStream();
    byte[] buffer=new byte[1024*4];
    int n=0;
    while ( (n=in.read(buffer)) !=-1) {
      out.write(buffer,0,n);
    }
    return out.toByteArray();
  }


  /**
   * @throws IOException
   * @throws MalformedURLException
   * 网络文件转换为本地文件
   * @Title: toByteArray
   * @param @param url
   * @param @return
   * @param @throws IOException    设定文件
   * @return byte[]    返回类型
   * @throws
   */
  public static void toBDFile(String urlStr, String bdUrl) throws IOException,UnknownHostException{
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    DataInputStream in = new DataInputStream(conn.getInputStream());
    byte[] data=toByteArray(in);
    in.close();
    FileOutputStream out=new FileOutputStream(bdUrl);
    out.write(data);
    out.close();
  }

}
